 <template>
  <div>
    <Row>
      <i-col span="24" style="text-align: right;">
        <Button type="primary" icon="ios-copy" @click="preShow" class="tiy_btn">预览</Button>
        <Button type="success" style="margin-right: 3rem" icon="ios-send-outline" @click="sendEmail" class="tiy_btn">发送</Button>
      </i-col>
    </Row>
    <Form :model="email"   :label-width="120" ref="androidForm"  :rules="emailRule" style="margin:1rem 0px 1rem 0px">
      <FormItem label="收件人 :">
        <Row>
          <i-col v-if="receiveUserHided.length>0" span="20">
            <span v-for="(item,index) in receiveUserHided">
                <Tag size="medium" type="border" color="primary" closable @on-close="handleClose(index)">
                  <span v-if="isNotEmpty(item.contactEmail)">{{item.contactEmail}}</span>
               </Tag>
            </span>
            <Button icon="ios-add" type="primary" size="small" @click="showAddEmail">添加邮箱</Button>
          </i-col>
          <i-col v-if="receiveUserHided.length===0" span="20">
            <Input v-model.trim="receiverEmail" placeholder="多个收件人以英文逗号分割" style="width: 100%" />
          </i-col>
        </Row>
      </FormItem>

      <FormItem label="标题 :" prop="title">
        <Row>
          <i-col span="20">
            <Input  v-model.trim="email.title" type="textarea" placeholder="请输入" :autosize="{minRows: 1}" ></Input>
          </i-col>
        </Row>

      </FormItem>
      <FormItem label="正文 :" prop="content">
        <div style="margin-right: 8em;" class="">
          <quill-editor ref="myEditor" v-model="email.content" class="ql-editor ql-snow" :options="editorOption"></quill-editor>
        </div>
      </FormItem>
      <FormItem label="附件 :"  style="margin-top: 3rem">
        <Upload :action="uploadUrl" :before-upload="beforeUpload" :data="uploadFolderParam"
                :on-success="uploadImageSuccess" :on-progress="uploadImageProgress" multiple
                :on-error="uploadImageError" :show-upload-list="false"
                style="display: inline-block;" :max-size="1024*20" :on-exceeded-size="handleMaxSize">
          <Button type="primary" size="small" icon="ios-link">添加附件</Button>
        </Upload>
        <div v-for="(item,index) in fileList">
          <p class="file-list">{{item.name}} ({{item.size}})
            <span style="float:right;font-weight: bold" @click="deleteItem(index)">
                <Button type="text" shape="circle"  icon="md-close"></Button>
              </span>
          </p>
        </div>
      </FormItem>
    </Form>

    <Modal
      v-model="tStatus.modalEmailAdd.isShow"
      title="添加邮箱"
      :mask-closable="false"
      @on-ok="addEmail"
    >
      <Row style="margin:1rem;">
        <i-col span="24">
          <Input v-model.trim="emailInfo" placeholder="多个收件人以英文逗号分割" style="width: 100%" />
        </i-col>
      </Row>
    </Modal>


  </div>
</template>



<!--javascript 代码-->
<script>
  import Quill from 'quill'
  //图片resize
  import  ImageResize  from 'quill-image-resize-module';

  import tiyData from "./js/email/data"
  import {init,send,createContent} from "./js/email/funs"
  import {getfilesize,isNotEmpty} from "../js/commonUtils";
  import ApiBase from "../../api/moudles/ApiBase";


  Quill.register('modules/imageResize', ImageResize);
  let AlignAttr = Quill.import('attributors/style/align');
  let FontAttr = Quill.import('attributors/style/font');
  let SizeAttr = Quill.import('attributors/style/size');
  Quill.register(AlignAttr, true);
  Quill.register(FontAttr, true);
  Quill.register(SizeAttr, true);

  // 工具栏展示哪些功能按钮
  let toolOptions = [
    // [{ 'font': [] }],         //字体
    [{ 'header': [1, 2, 3, 4, 5,false]},{ size: ['small',false, 'large', 'huge'] }],         //几级标题
    ['bold', 'italic', 'underline', 'strike'],        //加粗，斜体，下划线，删除线
    ['blockquote','link'],         //引用，代码块
    [{ 'list': 'ordered'}, { 'list': 'bullet' }],          //列表
    [{ 'color': [] }, { 'background': [] }],          // 字体颜色，字体背景颜色
    [{ 'align': [] }],        //对齐方式
    ['image','video'],        //上传图片、上传视频,
    ['clean'],        //清除字体样式
  ];


  // 将图片存储为base64的方式改为只能引入URL类型的图片.
  let showImageUI = function (value) {
    if (value) {
      let href = prompt('输入图片地址');
      this.quill.format('image', href);
    } else {
      this.quill.format('image', false);
    }
  };

  export default {
    data(){
      return {
        editorOption:{
          placeholder: '邮件正文',
          modules: {
            imageResize: {
              displayStyles: {
                backgroundColor: 'black',
                border: 'none',
                color: 'white'
              },
              modules: ['Resize', 'DisplaySize', 'Toolbar']
            },
            toolbar:{
              container: toolOptions,
              handlers: {
                // image: showImageUI
              }
            }
          },
        },
        email:tiyData.tData.emailDetail,
        tStatus:tiyData.tStatus,
        emailRule: tiyData.tStatus.rules,
        yunPath: this.$store.getters.imgPrefix,
        uploadUrl:this.$apiOther.getUploadToOssUrl(),
        fileList:[],
        receiverEmail:'',
        emailInfo:'',
      }
    },
    computed: {
      receiveUserHided(){
        let self = this;
        let receiveUserHided = [];
        if(this.receiveUser){
            this.receiveUser.forEach(function (item) {
              receiveUserHided.push(item);
            });
        }
        return receiveUserHided;
      },
      uploadFolderParam (){
        let requestMsg = ApiBase.createRequestMsg({folder:'email/attachment/send'});
        return {requestMsg: JSON.stringify(requestMsg)};
      }
    },
    watch:{
      isRefresh(newVal,oldVal) {
        if(newVal){
          init(this,tiyData);
          // if(this.title){
          //     tiyData.tData.emailDetail.title = this.title;
          // }
          // if(this.text){
          //     tiyData.tData.emailDetail.content = this.text;
          // }
        }
      }
    },
    props:{
      receiveUser:[],
      isSend:"",//false 默认  true写邮件
      text:"", //初始化邮件内容
      title:"", //初始化邮件标题
      isRefresh:false,
    },
    methods: {
      showAddEmail(){
        this.emailInfo="";
        this.tStatus.modalEmailAdd.isShow=true;
      },
      addEmail(){
        if(isNotEmpty(this.emailInfo)){
          let receiveArray=this.emailInfo.split(",");
          for(let i=0;i<receiveArray.length;i++){
            let email=receiveArray[i];
            let one=email.indexOf('<');
            let two=email.indexOf('>');
            if(one==-1){
              let item={
                contactEmail:email,
              };
              this.receiveUser.push(item);
            }else{
              let item={
                contactEmail:email.slice(one+1,two),
              };
              this.receiveUser.push(item);
            }
          }
        }

      },
      handleClose(index){
        this.receiveUser.splice(index,1);
      },
      isNotEmpty(val) {
        return isNotEmpty(val);
      },
      preShow(){
        let win = window.open('', '效果预览窗口');
        win.document.open();
        win.document.write(createContent(this,tiyData));
        win.document.close();

      },
      sendEmail(){
        send(this,tiyData);
      },
      sendSuccess(){
        this.$emit("listenSendEmailEvent",true)
      },
      beforeUpload() {

      },
      deleteItem(index){
        this.fileList.splice(index,1);
      },
      uploadImageSuccess(response, file, fileList){
        if(response.success){
          let attachment={
            name:file.name,
            size:getfilesize(file.size),
            url:this.yunPath+response.result,
          }
          this.fileList.push(attachment);
        } else {
            this.$Message.error('上传图片失败！' + response.errorMessage) ;
        }
        this.$Spin.hide(); //隐藏遮罩层
      },
      uploadImageError(error, file, fileList){
        this.$Spin.hide();
      },
      uploadImageProgress(event, file, fileList){
        this.$Spin.show();
      },
      handleMaxSize(file){
        this.$Message.error(`文件: ${file.name} 太大, 不能超过 20M.`);
      }
    },
    created() {
      this.$watch("refresh",function(){
      });
      init(this,tiyData)
    }

  }
</script>

 <!--css样式-->
 <style scoped lang="less">
 @import  (once,optional)  "../css/base";
 @import "~quill/dist/quill.core.css";
 @import "~quill/dist/quill.snow.css";
 @import "~quill/dist/quill.bubble.css";
 .base_padding {
   padding: 20px;
   margin-bottom: 40px;
 }

 .file-list{
   background-color: #f5f5f5;
   max-width: 30rem;
   color: #7b74ea;
   margin-top:0.5rem;
   padding-left:0.8rem;
   font-weight: bold;
   font-size: small;
 }

 .quill-editor {
   height: 200px;
   overflow-y:visible;
   margin: 0rem 0rem 1rem 0rem;
   white-space: normal!important;
 }

 .quill-editor{
   img{
     width: 100%;
   }
 }



 .form_step {
   width:80%;
 }

 .ql-editor{
   min-height:28rem;
   margin-left: -1rem;
 }



 .form_value{
   text-align: left;
   max-width: 20em;
 }

 </style>
